package com.zznzzn.myweb.controller;


import com.zznzzn.myweb.exceptions.ServiceException;
import com.zznzzn.myweb.pojo.*;
import com.zznzzn.myweb.service.FavService;
import com.zznzzn.myweb.service.FileService;
import com.zznzzn.myweb.service.ItemService;
import com.zznzzn.myweb.service.UserService;
import com.zznzzn.myweb.util.Base64Util;
import com.zznzzn.myweb.util.RespHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
@RequestMapping("/api/item")
public class ItemController {
    @Autowired
    private UserService userService;

    @Autowired
    private FileService fileService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private FavService favService;

    @PostMapping("/deleteItem")
    public RespModel<Object> deleteItem(@RequestParam("itemid") String itemid) {
        try {
            itemService.deleteItem(itemid);
            return RespHelper.buildSuccess("删除成功");
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }

    }

    @PostMapping("/updateStatus")
    public RespModel<Object> updateStatus(
            @RequestParam("itemid") String itemid, @RequestParam("status") int status
    ) {
        try {
            itemService.updateStatus(itemid, status);
            return RespHelper.buildSuccess("修改成功", status);
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/listitems")
    public RespModel<Object> listItems(
            @RequestParam("uuid") String uuid,
            @RequestParam("level") int level
    ) {
        Map<String, Object> map = new HashMap<>();
        try {
            User looking = userService.harmless(userService.getUserById(uuid));

            //level   0 草稿   1 发布    2 已下单    3 交易完成   4 删除 5 异常查封
            //for user self set level to 4 so returns 0-3 level
            List<Item> items = itemService.getItemByUser(uuid, level);
            map.put("userinfo", looking);
            map.put("items", items);
            return RespHelper.buildSuccess("success", map);
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }


    }

    @PostMapping("/newitem")
    public RespModel<Object> newitem(
            @RequestParam("uuid") String uuid, @RequestParam("title") String btitle,
            @RequestParam("desc") String bdesc, @RequestParam("status") int status,
            @RequestParam("file") MultipartFile[] files, @RequestParam("price") double price,
            @RequestParam("postage") double postage
    ) {
        User user = userService.getUserById(uuid);
        String nickname = user.getNickname();
        String title = "";
        String desc = "";
        try {
            title = Base64Util.fullDecode(btitle);
            desc = Base64Util.fullDecode(bdesc);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            Item item = new Item(Base64Util.newUUID(), uuid, title, price, postage, desc, new Date(), 0, status, null);
            itemService.addItem(item);
            List<String> filenames = fileService.receivePictures(files, "魔盒@" + nickname);
            for (String filename : filenames) {
                File temp = new File(Base64Util.newUUID(), item.getItemid(), filename);
                fileService.insertFile(temp);
            }

            if (status == 0) {
                return RespHelper.buildSuccess("创建成功");
            } else {
                return RespHelper.buildSuccess("发布成功");
            }

        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/updateitem")
    public RespModel<Object> updateitem(
            @RequestParam("itemid") String itemid, @RequestParam("title") String btitle,
            @RequestParam("desc") String bdesc, @RequestParam("uuid") String uuid,
            @RequestParam("file") MultipartFile[] files, @RequestParam("price") double price,
            @RequestParam("postage") double postage, @RequestParam("existfilenames") String[] existfilenames
    ) {

        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
        }
        for (String s : existfilenames) {
            System.out.println(s);
        }

        String title = "";
        String desc = "";
        try {
            title = Base64Util.fullDecode(btitle);
            desc = Base64Util.fullDecode(bdesc);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            User user = userService.getUserById(uuid);
            Item item = itemService.getItemByItemid(itemid);
            String nickname = user.getNickname();
            item.setPrice(price);
            item.setPostage(postage);
            item.setTitle(title);
            item.setDescription(desc);

            //if has new file
            if (files != null) {
                List<String> filenames = fileService.receivePictures(files, "魔盒@" + nickname);
                for (String filename : filenames) {
                    File temp = new File(Base64Util.newUUID(), item.getItemid(), filename);
                    fileService.insertFile(temp);
                }
            }

            //delete useless file
            List<File> fileList = item.getFiles();
            for (File temp : fileList) {
                if (existfilenames == null) {
                    //delete all files under this item
                    fileService.deleteFile(temp.getFileid());
                    fileService.deleteLocalFile(temp.getFilename(), false);
                } else {
                    for (String recname : existfilenames) {
                        if (!temp.getFilename().equals(recname)) {
                            fileService.deleteFile(temp.getFileid());
                            fileService.deleteLocalFile(temp.getFilename(), false);
                        }
                    }
                }

            }

            itemService.updateItem(item);
            return RespHelper.buildSuccess("修改成功");

        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    //unauth
    @PostMapping("/listitem")
    public RespModel<Object> listItem(@RequestParam("itemid") String itemid) {
        try {
            Item item = itemService.getItemByItemid(itemid);
            return RespHelper.buildSuccess(item);
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }

    }

    //unauth
    @PostMapping("/allitems")
    public RespModel<Object> listItems(
           @RequestParam("offset") int offset, @RequestParam("size") int size,@RequestParam("uuid") String uuid
    ) {
        try {
            //here *exclude* uuid's items

            List<Item> items = itemService.getAllItemByTime(offset, size,uuid);
//            System.out.println("size of all items"+items.size());
            List<User> users = new ArrayList<>();
            for (Item item :items){
                users.add(userService.harmless(userService.getUserById(item.getUuid())));
            }
            Map<String,Object> map = new HashMap<>();
            map.put("users",users);
            map.put("items",items);
            return RespHelper.buildSuccess(map);
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/itemcounts")
    public RespModel<Object> listItems(@RequestParam("uuid") String uuid) {
        try {
            int items = itemService.itemCounts(uuid,4);
            return RespHelper.buildSuccess(items);
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }

    }

    @PostMapping("/addfav")
    public RespModel<Object> addfav(
            @RequestParam("uuid") String uuid,@RequestParam("itemid") String itemid
    ){
        try{
            Favourite favourite = new Favourite(Base64Util.newUUID(),uuid,itemid);
            favService.addFav(favourite);
            return RespHelper.buildSuccess("收藏成功");
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/delfav")
    public RespModel<Object> delfav(
            @RequestParam("itemid") String itemid,@RequestParam("uuid") String uuid
    ){
        try{
            favService.delFav(itemid,uuid);
            return RespHelper.buildSuccess("取消收藏成功");
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/listfav")
    public RespModel<Object> listfav(
            @RequestParam("uuid") String uuid
    ){
        try{
            List<Favourite> favouriteList = favService.getFavByUser(uuid);
            List<Item> items = new ArrayList<>();
            List<User> users = new ArrayList<>();
            for (Favourite fav:favouriteList){
                items.add(itemService.getItemByItemid(fav.getItemid()));
                users.add(userService.getUserById(fav.getUuid()));
            }
            Map<String,Object> map = new HashMap<>();
            map.put("items",items);
            map.put("users",users);
            return RespHelper.buildSuccess(map);
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }
}
